package com.gitee.feizns.quickstart.spring.data.jpa.page;

import com.gitee.feizns.quickstart.domain.page.LimitAo;
import com.gitee.feizns.quickstart.domain.page.PageAo;
import com.gitee.feizns.quickstart.domain.page.PageRecordsVo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

/**
 * spring data page 工具类
 * @author feizns
 * @since 2023/4/1
 */
public abstract class SpringDataPageUtils {

    /**
     * 从{@link PageAo}转换为{@link Pageable}
     * @return {@link Pageable}
     */
    public static Pageable apply(PageAo page) {
        return PageRequest.of(Math.toIntExact(page.getCurrent() - 1), Math.toIntExact(page.getSize()));
    }

    /**
     * 从{@link LimitAo}转换为{@link Pageable}
     * @param ao 分页限制参数
     * @return {@link Pageable}
     */
    public static Pageable apply(LimitAo ao) {
        return ao instanceof PageAo ? apply((PageAo) ao) : apply(new PageAo(ao.getLimit()));
    }

    /**
     * 从spring data的分页对象{@link Page}转换为{@link PageRecordsVo}
     * @param page {@link Page}
     * @return {@link PageRecordsVo}
     * @param <T> 分页数据类型
     */
    public static <T> PageRecordsVo<T> apply(Page<T> page) {
        return new SpringDataPageRecordsVoImplImpl<>(page);
    }

}
